import React, { Component } from 'react'
import { Input, Button, Icon, Table, Popconfirm, message, Form, Modal, Select, Option } from "antd";
import ArticleService from '../../service/article';

import {getCategoryList} from '../../service/category';

export default class Article extends Component {

  state = {
    items: [],
    selectedRows: [],
    categories: [],  // 文章分类
    keyword: '',
    editItem: null,
    isCreate: true,
    title: '',
    editVisible: false,
    commentVisible: false,
    pagination: {current: 1, pageSize: 5}
  }

  componentDidMount() {
    this.getList()

    getCategoryList({pageSize: 10}).then(res => {
      if (res.code == 0) {
        this.setState({categories: res.data.items})
      }
    })
  }

  pageChange = (current) => {
    this.setState({
      pagination: {...this.state.pagination, current}
    }, this.getList);
  }

  getList = ()=>{
    const {current: pageNum, pageSize} = this.state.pagination;
    const param = {
      pageNum, 
      pageSize, 
      keyword: this.state.keyword}
    ArticleService.getArticleList(param).then(res => {
      if(res.code === 0){
        const {pageNum: current, pageSize, total, items} = res.data;
        items.forEach(v => v.key = v._id);
        this.setState({
          items: res.data.items,
          pagination: {
            current, // 当前页
            pageSize, //每页的条数
            total, // 总条数
            showTotal: val => `总计${val}条`,
            onChange: this.pageChange
          }
        })
      
      }else{
        message.error(res.error);
      }
    })
  }

  // 添加文章
  create = () => {
    this.setState({title: '添加文章', isCreate: true, editVisible: true})
  }

  // 点击确定
  editOk = () => {
    let form = this.editfrom.props.form;
    // 校验表单函数
    form.validateFieldsAndScroll((err, values) => {
      if (err) return;
      let article = form.getFieldsValue();
      console.log(article);
      let actionFn = this.state.isCreate ? ArticleService.addArticle: ArticleService.updateArticle;
      actionFn(article).then(res => {
        if(res.code === 0){
          message.success(res.data);
          this.setState({editVisible: false}, this.getList)
        }else{
          message.error(res.error);
        }
      })
    })
  }
  // 编辑
  editAction = (item) => {
    this.setState({title: '编辑文章', isCreate: false, editVisible: true, editItem: item})
  }
  removeItem = (item) => {
    let params = {}
    if (!item) {
      if (!this.state.selectedRows.length) {
        return message.error('请选择要删除的行')
      }
      params.ids = this.state.selectedRows.reduce((pre, cur) => `${pre._id},${cur._id}`).split(',')
      params.id = params.ids[0];
    }else{
      params.id = item._id;
    }
    if (!params.id) {
      return
    }
    ArticleService.delArticle(params).then(res => {
      if(res.code === 0){
        message.success(res.data)
        this.setState({pagination: {...this.state.pagination, current: 1}}, this.getList)
      }else{
        message.error(res.error);
      }
    })
  }

  // 查看文章
  checkArticle = (item) => {
    ArticleService.checkArticle({id: item._id}).then(res => {
      if(res.code === 0){
        message.success(res.data)
        this.getList()
      }else{
        message.error('查看失败');
      }
    })
  }
  commentAction = (item) => {
    this.setState({commentVisible: true, editItem: item})
  }
  // 提交评论
  submitComment = () => {
    let form = this.commentfrom.props.form;
    // 校验表单函数
    form.validateFieldsAndScroll((err, values) => {
      if (err) return;
      let comment = form.getFieldsValue();

      ArticleService.commentArticle(comment).then(res => {
        if(res.code === 0){
          message.success(res.data);
          this.setState({commentVisible: false}, this.getList)
        }else{
          message.error(res.error);
        }
      })
    })
  }
  
  render() {
    const columns = [
      {
        title: '标题',
        dataIndex: 'title',
        key: 'title'
      },{
        title: '分类',
        dataIndex: 'category',
        key: 'category',
        render: (text, record) => {
          if (text) {  // text是个对象， 返回对象中的一个字段 populate后text变成分类对象
            return text.name;
          } 
        }
      },
      {
        title: '阅读量',
        dataIndex: 'pv',
        key: 'pv'
      },{
        title: '创建时间',
        dataIndex: 'createAt',
        key: 'createAt',
        render: text => text.toLocaleString()
      },
      {
        title: '评论数',
        dataIndex: 'comments',
        key: 'comments',
        render: text => text.length
      },
      {
        title: '操作',
        render: (text, record, index) => {
          return (
            <Button.Group value="small">
              <Button value="small" type="primary" onClick={() => this.checkArticle(record)}>查看</Button>

              <Button value="small" type="primary" onClick={() => this.editAction(record)}>编辑</Button>
              <Button value="small" type="primary" onClick={() => this.commentAction(record)}>评论</Button>
              <Popconfirm
                title="是否确认删除该分类?"
                onConfirm={() => this.removeItem(record)}
              >
                <Button value="small" type="danger">删除</Button>
              </Popconfirm>
              
            </Button.Group>
          );
        }
      },
    ];

    const rowSelection = {
      onChange: (selectedRowKeys, selectedRows) => {
        this.setState({selectedRows})
      },
      getCheckboxProps: record => ({
        disabled: record.name === 'Disabled User', // Column configuration not to be checked
        name: record.name,
      }),
    };

    return (
      <div style={{padding: 15}}>
        <Input.Search 
          placeholder="请输入搜索内容" 
          onSearch={keyword => this.setState({keyword}, this.getList)} 
          enterButton />
        <Button.Group style={{marginTop: 10, marginBottom: 20}}>
          <Button type="primary" onClick={this.create}>
            <Icon type="plus" />
            添加
          </Button>
          <Button type="danger" onClick={() => this.removeItem()}>
            <Icon type="delete" />
            批量删除
          </Button>
        </Button.Group>
        <Table 
          pagination={this.state.pagination} 
          dataSource={this.state.items} 
          columns={columns} 
          rowSelection={rowSelection}
        />
        {/* 编辑或新增弹框 */}
        <Modal 
          visible={this.state.editVisible}
          title={this.state.title}
          destroyOnClose
          onCancel={() => this.setState({editVisible: false})}
          onOk={this.editOk}
        >
          <WrappedEditModal 
            wrappedComponentRef={inst => this.editfrom = inst}
            editItem={this.state.editItem}
            isCreate={this.state.isCreate}
            categories={this.state.categories}
          />
        </Modal>
        {/* 评论弹框 */}
        <Modal
          destroyOnClose
          title="评论文章"
          visible={this.state.commentVisible}
          onCancel={() => this.setState({commentVisible: false})}
          onOk={this.submitComment}
        >
          <WrappedCommentModal 
            editItem={this.state.editItem}
            wrappedComponentRef={inst => this.commentfrom = inst}
          />
        </Modal>
      </div>
    )
  }
}

class EditModal extends Component{
  render() {
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 4 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 19 },
      },
    };

    const {getFieldDecorator} = this.props.form;
    return (
       <Form {...formItemLayout}>
         <Form.Item label="分类">
          {
            getFieldDecorator('category', {
              initialValue: this.props.isCreate? '': this.props.editItem.category._id,
              rules: [{required: true, message: '请选择文章分类'}]
            })(
              <Select placeholder="请选择文章分类"> 
                {
                  this.props.categories.map(v => {
                    return <Select.Option key={v._id} value={v._id}>{v.name}</Select.Option>
                  })
                }
              </Select>
            )
          }
         </Form.Item>
         <Form.Item label="标题">
          {
            getFieldDecorator('title', {
              initialValue: this.props.isCreate? '': this.props.editItem.title,
              rules: [{required: true, message: '请输入文章标题'}]
            })(<Input placeholder="请输入文章标题" />)
          }
         </Form.Item>

         <Form.Item label="内容">
          {
            getFieldDecorator('content', {
              initialValue: this.props.isCreate? '': this.props.editItem.content,
              rules: [{required: true, message: '请输入文章内容'}]
            })(<Input.TextArea placeholder="请输入文章内容" />)
          }
         </Form.Item>
         {
          !this.props.isCreate && (
            <Form.Item>
              {
                getFieldDecorator('id', {
                  initialValue: this.props.editItem._id,
                })(<Input type="hidden" />)
              }
            </Form.Item>
          )
          }
       </Form>
    );
  }

}

const WrappedEditModal = Form.create()(EditModal);


class CommentModal extends Component{

  render() {
    const {getFieldDecorator} = this.props.form;

    return (
       <Form>
         <Form.Item label="评论">
          {
            getFieldDecorator('content', {
              rules: [{required: true, message: '请输入评论内容'}]
            })(<Input.TextArea placeholder="请输入评论内容" />)
          }
         </Form.Item>
         <Form.Item>
            {
              getFieldDecorator('id', {
                initialValue: this.props.editItem._id,
              })(<Input type="hidden" />)
            }
         </Form.Item>
       </Form>
    );
  }
}

const WrappedCommentModal = Form.create()(CommentModal);
